/*
 * FileUtil.cc
 *
 *  Created on: 2021年4月5日
 *      Author: san
 */

#include "FileUtil.h"
#include <assert.h>
#include <stdio.h>

namespace san {

AppendFile::AppendFile(const std::string &filename)
	: fp_(fopen(filename.c_str(), "ae"))
{
//	if (fp_ = fopen(filename.c_str(), "ae"))
//	{
//		fprintf(stderr, "Fail to open file!: %s\n", filename.c_str());
//	}

	assert(fp_);
	setbuffer(fp_, buffer_, sizeof buffer_);
}

AppendFile::~AppendFile()
{
	fclose(fp_);
}

void AppendFile::append(const char *logline, const size_t len)
{
	size_t n = this->write(logline, len);
	size_t remain = len - n;
	while ( remain > 0)
	{
		size_t x = this->write(logline, len);
		if (x == 0)
		{
			int err = ferror(fp_);
			if (err)
			{
				fprintf(stderr, "AppendFile::Append() Failed!\n");
				break;
			}
		}
		n += x;
		remain = len - n;
	}
}

void AppendFile::flush()
{
	fflush(fp_);
}

size_t AppendFile::write(const char *logline, size_t len)
{
	// 使用单独一个线程来记录日志
	return fwrite_unlocked(logline, 1, len, fp_);
}

} /* namespace san */
